import { calendarApi } from '../../api/clockIn.js'
import tools from '../../tools/tools.js'
import store from '../../utils/store.js'
import Toast from '@vant/weapp/toast/toast';

const today = tools.formatDate(new Date())

Page({
  /**
   * 页面的初始数据
   */
  data: {
    today,
    currentMonth: tools.formatDate(new Date(), 'yyyy-MM'),
    calendarData: {
      loading: false,
      tip: true,
      minDate: "2024-01-01",
      maxDate: tools.formatDate(new Date()), // 最大日期设为今天
      todos: [],
      date: today,
      isOne: true,
      weight: '', // 体重数据
      trainDesc: '', // 训练描述
      trainStatus: false, // 训练打卡状态
      weightStatus: false // 体重打卡状态
    },
    isClock: {
      weight: false,
      train: false,
      today: true
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getcalendarData(this.data.currentMonth)
    // 初始化当天打卡状态
    this.updateCheckInStatus(today)
  },

  /**
   * 过滤打卡数据
   */
  filterCheckInData(data) {
    return data.map((item, index) => {
      const { date, diary, weight, trainContent } = item
      let title, type

      if (diary && weight) {
        title = '全部打卡'
        type = 1
      } else if (!diary && weight) {
        title = '体重打卡，训练未打卡'
        type = 2
      } else if (diary && !weight) {
        title = '体重未打卡，训练打卡'
        type = 3
      } else {
        title = '体重未打卡，训练未打卡'
        type = null
      }

      return {
        id: index + 1,
        date,
        title,
        type,
        weight, // 体重数值
        trainContent // 训练内容
      }
    })
  },

  /**
   * 获取日历数据
   */
  async getcalendarData(date) {
    // console.log('请求日历数据：', date)

    if (!date || !store.state.studentId) {
      console.error('日历数据请求失败：入参不完整')
      Toast.fail('请求参数异常，请刷新页面重试')
      return
    }

    try {
      this.setData({ 'calendarData.loading': true })
      const calendarRes = await calendarApi({
        studentId: store.state.studentId,
        date
      })

      if (!calendarRes || !Array.isArray(calendarRes)) {
        throw new Error('接口返回数据格式异常')
      }

      const allData = this.filterCheckInData(calendarRes)
      console.log('处理后的日历数据：', allData)

      this.setData({
        'calendarData.todos': [...allData],
        'calendarData.loading': false
      }, () => {
        // 在 setData 的回调中更新打卡状态，确保 todos 已更新
        this.updateCheckInStatus(this.data.calendarData.date);
      })

    } catch (error) {
      console.error('日历数据请求异常：', error)
      this.setData({ 'calendarData.loading': false })

      let errorMsg = '日历数据加载失败'
      if (error.message.includes('网络')) {
        errorMsg = '网络异常，请检查网络连接'
      } else if (error.message.includes('接口返回')) {
        errorMsg = error.message
      } else {
        errorMsg = '数据加载异常，请刷新页面重试'
      }
      Toast.fail(errorMsg)

      this.setData({ 'calendarData.todos': [] })
    }
  },

  /**
   * 更新打卡状态
   */
  updateCheckInStatus(date) {
    const { todos } = this.data.calendarData
    const targetTodo = todos.find(todo => todo.date === date)

    if (targetTodo) {
      this.setData({
        'calendarData.weight': targetTodo.weight || '',
        'calendarData.trainDesc': targetTodo.trainContent || '',
        'calendarData.weightStatus': !!targetTodo.weight,
        'calendarData.trainStatus': !!targetTodo.trainContent
      })
    } else {
      this.setData({
        'calendarData.weight': '',
        'calendarData.trainDesc': '',
        'calendarData.weightStatus': false,
        'calendarData.trainStatus': false
      })
    }
  },

  /**
   * 月份变化事件
   */
  onCalendarMonthChange(e) {
    // console.log('月份变化：', data)
    // const { month, year } = data.detail
    // const requestDate = `${year}-${month.toString().padStart(2, '0')}`
    // this.setData({ currentMonth: requestDate })
    // this.getcalendarData(requestDate)

    console.log('测试页面：月份变化事件触发', e.detail);
    const { year, month } = e.detail;
    const newMonthStr = `${year}-${month.toString().padStart(2, '0')}`;
    this.setData({
      currentMonth: newMonthStr
    }, () => {
      const newTodos = [
        { id: 1, date: `${year}-${month.toString().padStart(2, '0')}-05`, type: 3, title: '训练打卡' },
        { id: 2, date: `${year}-${month.toString().padStart(2, '0')}-06`, type: 1, title: '全部打卡' }
      ];

      this.getcalendarData(newMonthStr)
      console.log('测试页面：模拟更新 todos', newTodos);
      // this.setData({ 'calendarData.todos': newTodos });
    })
    // 模拟父组件请求数据后更新 todos
    // setTimeout(() => {
    //   const newTodos = [
    //     { id: 1, date: `${year}-${month.toString().padStart(2, '0')}-05`, type: 3, title: '训练打卡' },
    //     { id: 2, date: `${year}-${month.toString().padStart(2, '0')}-06`, type: 1, title: '全部打卡' }
    //   ];
    //   console.log('测试页面：模拟更新 todos', newTodos);
    //   this.setData({ todos: newTodos });
    // }, 500);
  },

  /**
   * 日期选择事件
   */
  onDateChange(e) {
    console.log('选中日期：', e)
    const clickDate = e.detail.date
    // const isOne = tools.isWithinNumberDays(clickDate, today)
    // console.log(isOne, 'isOne')
    console.log(e.detail.hasHalfTodo, e.detail.date == this.data.today)
    this.setData({
      'calendarData.date': clickDate,
      'isClock.weight': e.detail.hasTodo || e.detail.hasHalfTodo,
      'isClock.train': e.detail.hasTodo || e.detail.hasBothTodo,
      'isClock.today': e.detail.date == this.data.today
    })
  },

  /**
   * 去体重打卡页面
   */
  goClickIn() {
    const { date, isOne } = this.data.calendarData
    if (!isOne) {
      Toast('只能打卡当天日期')
      return
    }
    wx.navigateTo({
      url: `/clockInPage/deviceMeasure/deviceMeasure?date=${date}`
    })
  },

  /**
   * 训练打卡
   */
  goTrainRecord(event) {
    const { type } = event.currentTarget.dataset
    const { date } = this.data.calendarData
    
    // 打卡操作只能在当天进行
    // if (type === '2' && !isOne) {
    //   Toast('只能打卡当天日期')
    //   return
    // }

    wx.navigateTo({
      url: `/clockInPage/trainingRecord/trainingRecord?type=${type}&date=${date}`
    })
  },

  /**
   * 训练历史页面
   */
  goTrainHistory(event) {
    // type 1: 体重  2: 训练
    const { type } = event.currentTarget.dataset
    wx.navigateTo({
      url: `/clockInPage/trainHistory/trainHistory?type=${type}`
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.getcalendarData(this.data.currentMonth)
    wx.stopPullDownRefresh()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 从打卡页面返回时刷新数据
    this.getcalendarData(this.data.currentMonth)
  }
})